//
//  GTGuideDetailViewController.m
//  GiftTalk
//
//  Created by Wan on 16/4/4.
//  Copyright © 2016年 Wan. All rights reserved.
//  搜索结果 -> 攻略

#import "GTGuideDetailViewController.h"
#import <AFNetworking.h>
#import "GTGuideBottomToolBar.h"
#import "GTUMSocialShare.h"
#import "GTGuideWebViewBottomToolBar.h"
#import "GTGuideDetail.h"
#import <SVProgressHUD.h>
#import <MJRefresh.h>
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import "GTGiftDetailViewController.h"
#import "GTCommentViewController.h"

@interface GTGuideDetailViewController () <UIScrollViewDelegate, UIWebViewDelegate>

/** 攻略 webView 底部工具条 */
@property (weak, nonatomic) GTGuideWebViewBottomToolBar *guideWebViewBottomToolBar;
/** 攻略底部工具条 */
@property (weak, nonatomic) GTGuideBottomToolBar *guideBottomToolBar;
/** 图片上的标题 */
@property (weak, nonatomic) UILabel *titleLabel;
/** <#注释#> */
@property (weak, nonatomic) UIWebView *webView;
/** 头部视图图像 */
@property (weak, nonatomic) UIImageView *headerImageView;

/** 请求管理者 */
@property (strong, nonatomic) AFHTTPSessionManager *manager;
/** 攻略内容模型 */
@property (strong, nonatomic) GTGuideDetail *guideDetail;

@end

static const CGFloat GTGuideDetailHeaderH = 200;
static const CGFloat GTGuideDetailTitleBottomMargin = 15;
static const CGFloat GTGuideDetailTitleLeftMargin = 15;

#define GTGuideDetailTitleFont [UIFont systemFontOfSize:25.0]

@implementation GTGuideDetailViewController

- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.session.configuration.timeoutIntervalForRequest = GTTimeoutIntervalForRequest;
    }
    return _manager;
}

- (GTGuideDetail *)guideDetail {
    if (!_guideDetail) {
        _guideDetail = [[GTGuideDetail alloc] init];
    }
    return _guideDetail;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    
    [self setupHeaderViewImage];
    
    [self setupWebView];
    
    [self setupTittleLabel];

    [self loadData];
    
    [self setupGuideBottomToolBar];
    
    [self setupGuideWebViewBottomToolBar];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [SVProgressHUD dismiss];
}

#pragma  mark - 初始化
- (void)setupNav {
    self.view.backgroundColor = GTBackgroundColor;
    self.title = @"攻略详情";
}

- (void)setupHeaderViewImage {
    // 先添加 UIImageView
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(0, self.navigationController.navigationBar.height + GTStatusBarH, GTScreenW, GTGuideDetailHeaderH);
    [self.view addSubview:imageView];
    self.headerImageView = imageView;
    
    // 设置阴影
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(id)[UIColor clearColor].CGColor, (id)[UIColor blackColor].CGColor];
    gradientLayer.opacity = 0.6;
    gradientLayer.frame = self.headerImageView.bounds;
    [self.headerImageView.layer addSublayer:gradientLayer];
}

- (void)setupWebView {
    // d
    UIWebView *webView = [[UIWebView alloc] init];
//    webView.backgroundColor = GTBackgroundColor;
    webView.backgroundColor = [UIColor clearColor];
    webView.frame = GTScreenBounds;
    webView.scrollView.backgroundColor = [UIColor clearColor];
    webView.scrollView.delegate = self;
    webView.delegate = self;
    
    // 设置 webView 顶部偏移和底部偏移
    webView.scrollView.contentInset = UIEdgeInsetsMake(GTGuideDetailHeaderH + self.navigationController.navigationBar.height, 0, 0, 0);
    webView.scrollView.contentOffset = CGPointMake(0, -GTGuideDetailHeaderH - self.navigationController.navigationBar.height - GTStatusBarH);
    [self.view addSubview:webView];
    self.webView = webView;
}

/**
 *  初始化图片上的标题
 */
- (void)setupTittleLabel {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = GTGuideDetailTitleFont;
    titleLabel.numberOfLines = 0;
    titleLabel.textColor = [UIColor whiteColor];
    [self.webView.scrollView addSubview:titleLabel];
    self.titleLabel = titleLabel;
}

#pragma mark - 加载数据
- (void)loadData {
    NSString *guideDetailUrlStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/posts/%ld", self.ID];
    [SVProgressHUD showWithStatus:@"正在加载图片详情"];
    
    [self.manager GET:guideDetailUrlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismiss];
        
        self.guideDetail = [GTGuideDetail mj_objectWithKeyValues:responseObject[@"data"]];
        
        // 设置 webView 和 imageView 的内容
        [self.webView loadHTMLString:self.guideDetail.content_html baseURL:nil];
        [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:self.guideDetail.cover_image_url] placeholderImage:[UIImage imageNamed:@"app_logo"]];
        
        self.guideBottomToolBar.guideDetail = self.guideDetail;
        self.guideWebViewBottomToolBar.guideDetail = self.guideDetail;
        
        // 设置标题坐标
        [self adjustTitleLabelFrameWithText:self.guideDetail.title];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"服务器繁忙，请稍后再试！"];
    }];
}

- (void)setupGuideBottomToolBar {
    GTGuideBottomToolBar *guideBottomToolBar = [GTGuideBottomToolBar guideBottomToolBar];
    guideBottomToolBar.width = GTScreenW;
    guideBottomToolBar.centerY = GTScreenH - guideBottomToolBar.height / 2.0;
    [self.view addSubview:guideBottomToolBar];
    self.guideBottomToolBar = guideBottomToolBar;
}

- (void)setupGuideWebViewBottomToolBar {
    GTGuideWebViewBottomToolBar *guideWebViewBottomToolBar = [GTGuideWebViewBottomToolBar guideWebViewBottomToolBar];
    guideWebViewBottomToolBar.width = GTScreenW;
    guideWebViewBottomToolBar.y = self.webView.scrollView.contentSize.height;
    [self.webView.scrollView addSubview:guideWebViewBottomToolBar];
    self.guideWebViewBottomToolBar = guideWebViewBottomToolBar;
    
    // 设置下边距
    UIEdgeInsets edgeInset = self.webView.scrollView.contentInset;
    edgeInset.bottom += guideWebViewBottomToolBar.height;
    self.webView.scrollView.contentInset = edgeInset;
    
    [guideWebViewBottomToolBar addReplyButtonTarget:self action:@selector(replyButtonClick)];
    /*
    [guideWebViewBottomToolBar addFavoriteButtonTarget:self action:@selector(likeButtonClick:)];
    [guideWebViewBottomToolBar addShareButtonTarget:self action:@selector(shareButtonClick)];
    */
}

- (void)replyButtonClick {
    GTCommentViewController *commentVc = [[GTCommentViewController alloc] init];
    [self.navigationController pushViewController:commentVc animated:YES];
}

/**
 *  调整标题位置
 */
- (void)adjustTitleLabelFrameWithText:(NSString *)text {
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = GTGuideDetailTitleFont;
    CGSize size = [text boundingRectWithSize:CGSizeMake(GTScreenW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    self.titleLabel.text = text;

    CGFloat y = size.height + GTGuideDetailTitleBottomMargin;
    CGFloat w = GTScreenW - GTGuideDetailTitleBottomMargin;
    self.titleLabel.frame = CGRectMake(GTGuideDetailTitleLeftMargin, -y, w, size.height);
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat upRate = 0.4;
    CGFloat downScale = 2.0;
    
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat insetTop = scrollView.contentInset.top;
    
    if (ABS(offsetY) < insetTop) {
        // 往上移，图片也往上移
        CGFloat y = - (offsetY + insetTop) * upRate;
        self.headerImageView.transform = CGAffineTransformMakeTranslation(0, y);
    } else if (ABS(offsetY + insetTop) < GTGuideDetailHeaderH / downScale) {
        // 往下移小于图片高度的一半，图片进行放大
        CGFloat scale = - (offsetY + insetTop) / GTGuideDetailHeaderH * downScale + 1;
        self.headerImageView.transform = CGAffineTransformMakeScale(scale, scale);
    } else {
        // 往下移大于图片高度的一半，图片随 scrollView 一起向下移
        CGFloat y = ABS(offsetY) - insetTop - GTGuideDetailHeaderH / downScale;
        self.headerImageView.transform = CGAffineTransformMakeTranslation(0, y);
        self.headerImageView.transform = CGAffineTransformScale(self.headerImageView.transform, downScale, downScale);
    }
    
    // 拉到底部时，toolBar 往下移
    CGFloat scrollViewHeight = scrollView.contentSize.height;
    if (offsetY + GTScreenH > scrollViewHeight) {
        CGFloat scale = self.guideBottomToolBar.height / self.guideWebViewBottomToolBar.height;
        self.guideBottomToolBar.y = GTScreenH - self.guideBottomToolBar.height + (offsetY + GTScreenH - scrollView.contentSize.height) * scale;
    } else {
        // 滑动并不会很准确，这句代码用来确定底部 toolBar 的 y 轴
        self.guideBottomToolBar.y = GTScreenH - self.guideBottomToolBar.height;
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (!self.guideWebViewBottomToolBar) {
        // 使用 webView 加载完成后得到的 contentSize 不准确
        [self setupGuideWebViewBottomToolBar];
    }
    self.guideWebViewBottomToolBar.y = scrollView.contentSize.height;
}

#pragma mark - <UIWebViewDelegate>
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        // 点击内部详情链接，跳转到礼物详情界面
        NSArray *urlParam = [request.URL.absoluteString componentsSeparatedByString:@"/"];
        GTGiftDetailViewController *giftDetailVc = [[GTGiftDetailViewController alloc] init];
        giftDetailVc.giftId = [urlParam lastObject];
        [self.navigationController pushViewController:giftDetailVc animated:YES];
        return NO;
    }
    return YES;
}

#pragma mark - 攻略页面

- (void)dealloc {
    [self.manager invalidateSessionCancelingTasks:YES];
}
@end
